package com.xzlf.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class MsgDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        // Tcp 拆包 粘包问题
        if (byteBuf.readableBytes() < 8)
            return;
        byteBuf.markReaderIndex();
        MsgType msgType = MsgType.values()[byteBuf.readInt()];
        int length = byteBuf.readInt();
        if (byteBuf.readableBytes() < length){
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        switch (msgType){
            case TankJoin:
                TankJoinMsg msg = new TankJoinMsg();
                msg.parseBytes(bytes);
                list.add(msg);
                break;
            default:
                break;

        }

        TankJoinMsg msg = new TankJoinMsg();


        list.add(msg);
    }
}
